package com.recursivechaos.examples.sqlwatcher;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.recursivechaos.examples.sqlwatcher.sql.MySQLAccess;

public class MainSqlWatcher {
	public static void main(String[] args) {
		// Create persistent objects
		Logger logger = LoggerFactory.getLogger(MainSqlWatcher.class);
		int continueLoop = 0;
		
		// Test array
		List<Integer> times = new ArrayList<Integer>();
		
		// Begin loop here
		do{
			
			// Create rebuilding objects
			long start	= 0;
			long end	= 0;
			MySQLAccess dao = new MySQLAccess();
			
			// Attempt Query
		    try {
		    	logger.debug("Begin ping database.");
				start = (System.nanoTime()/1000000);
				dao.readDataBase();
				end = (System.nanoTime()/1000000);
				logger.debug("Database pinged.");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    
		    // Do math
		    //double seconds = (end - start) / 1000000000.0;
		    // TODO: Fix ~1ms loss of precision
		    int milsec = (int) (end-start);
			//System.out.println(seconds + " seconds elapsed");
			System.out.println(milsec + " milliseconds elapsed");
			
			times.add(milsec);
			System.out.println("Average: " + getAverage(times));
			
			// Wait
			try {
				// 1000 = 1 second
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			// end loop
		}while(continueLoop==0);
	}

	private static int getAverage(List<Integer> times) {
		int avg = 0;
		int sum = 0;
		
		Iterator<Integer> it = times.iterator();
		while(it.hasNext()){
			if(times.size()>50){
				times.remove(0);
			}
			Integer time = it.next();
			sum+=time;
		}
		avg = (sum/times.size());
		
		
		return avg;
	}

}
